﻿#include "RulerDataAddDlg.h"
#include "ui_RulerDataAddDlg.h"
#include <QUuid>
#include "DBManage.h"

RulerDataAddDlg::RulerDataAddDlg(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::RulerDataAddDlg)
{
    ui->setupUi(this);
    this->setAttribute(Qt::WA_ShowModal, true);

    ui->spinBox_startTime->setRange(-9999, 9999);
    ui->spinBox_endTime->setRange(-9999, 9999);

    m_rulerID = "";
    m_isModify = false;

    connect(ui->pushButton_save, SIGNAL(clicked()), this, SLOT(slotSaveRulerData()));
    connect(ui->pushButton_cancel, SIGNAL(clicked()), this, SLOT(close()));
    ui->comboBox->setEnabled(true);
}

RulerDataAddDlg::~RulerDataAddDlg()
{
    delete ui;
}

void RulerDataAddDlg::clearContents()
{
    m_isModify = false;
    ui->spinBox_startTime->setValue(0);
    ui->spinBox_endTime->setValue(0);
    ui->lineEdit_name->clear();
    ui->lineEdit_templeName->clear();
    ui->lineEdit_posthumousName->clear();
    updateCountryItems();

    m_rulerID = QUuid::createUuid().toString();
    ui->lineEdit_rulerID->setText(m_rulerID);
}

void RulerDataAddDlg::setData(const Ruler &data)
{
    m_isModify = true;
    updateCountryItems();

    ui->spinBox_startTime->setValue(data.startTime);
    ui->spinBox_endTime->setValue(data.endTime);
    ui->lineEdit_name->setText(data.rulerName);
    int currentIndex = ui->comboBox->findData(data.countryID);  // 按照countryID找是哪个政权
    ui->comboBox->setCurrentIndex(currentIndex);
    ui->lineEdit_templeName->setText(data.templeName);
    ui->lineEdit_posthumousName->setText(data.posthumousName);

    m_rulerID = data.rulerID;
    ui->lineEdit_rulerID->setText(m_rulerID);
}

void RulerDataAddDlg::slotSaveRulerData()
{
    Ruler data;

    data.startTime = ui->spinBox_startTime->value();
    data.endTime = ui->spinBox_endTime->value();
    data.rulerName = ui->lineEdit_name->text();
    QString countryID = ui->comboBox->currentData().toString();
    data.countryID = countryID;
    data.rulerID = m_rulerID;
    data.templeName = ui->lineEdit_templeName->text();
    data.posthumousName = ui->lineEdit_posthumousName->text();

    emit sigRulerData(data, m_isModify);
    this->close();
}

void RulerDataAddDlg::updateCountryItems()
{
    ui->comboBox->blockSignals(true);
    ui->comboBox->clear();
    m_lstCountry.clear();

    m_lstCountry = DBManage::getInstance()->getCountryDatas();
    for(int i = 0;  i < m_lstCountry.size(); ++i)
    {
        ui->comboBox->addItem(m_lstCountry[i].countryName, m_lstCountry[i].countryID);
    }
    ui->comboBox->setCurrentIndex(-1);
    ui->comboBox->blockSignals(false);
}
